package com.ly.mp.dal.comm.jdbc;

import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.jdbc.datasource.lookup.DataSourceLookup;

public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final Logger log = LoggerFactory.getLogger(DynamicDataSource.class);
    public static final String DATASOURCE_BEAN_CLASS = "com.alibaba.druid.pool.DruidDataSource";
    private int readDBSize;

    // 读库只能随机切换
    protected Object determineCurrentLookupKey() {
        String dsKey = ReadWriteDataSourceDecision.getDsKey();
        if (ReadWriteDataSourceDecision.isChoiceRead() && this.readDBSize > 0) {
            dsKey = dsKey == null ? "default_readDBKey" : dsKey;
            dsKey = dsKey + "#" + RandomUtils.nextInt(this.readDBSize);
        }

        log.info("当前数据源key:{}", dsKey);
        return dsKey;
    }
    
    public DataSource getAcuallyDataSource() {
        Object lookupKey = determineCurrentLookupKey();
        if(null == lookupKey) {
            return this;
        }
        DataSource determineTargetDataSource = this.determineTargetDataSource();
        return determineTargetDataSource==null ? this : determineTargetDataSource;
    }

    public void setDataSourceLookup(DataSourceLookup dataSourceLookup) {
        super.setDataSourceLookup(dataSourceLookup);
    }

    public void setDefaultTargetDataSource(Object defaultTargetDataSource) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
    }

    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
    }

    public DataSource getTargetDataSource() {
        return this.determineTargetDataSource();
    }

    public void setReadDBSize(int readDBSize) {
        this.readDBSize = readDBSize;
    }

    public int getReadDBSize() {
        return this.readDBSize;
    }
}